package com.kly.user.msgClient;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.common.utils.TimeUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kly.enums.ParameterTypeEnum;
import com.kly.enums.PushAPIEnum;
import com.kly.service.MemberService;
import com.kly.user.chatterService.ChatService;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.*;
import com.kly.user.dto.ExtendInfoDto;
import com.kly.user.dto.UserInterestDto;
import com.kly.user.dto.WlmUserDto;
import com.kly.user.dto.chatter.response.ChatListDto;
import com.kly.user.dto.chatter.response.UserAccount;
import com.kly.user.enums.*;
import com.kly.user.eventbus.Event;
import com.kly.user.task.enums.TaskStatusEnum;
import com.kly.user.task.enums.TaskTypeEnum;
import com.kly.user.task.service.CommonUtilityService;
import com.kly.user.utils.ImagePrefixUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * msg api调用处理类
 *
 * @author linqu
 */
@Component
public class MsgAPI extends ApiClient {

    private static Log logger = LogFactory.getLog(MsgAPI.class);

    @Resource
    UserAccessDao userAccessDao;
    @Resource
    UserChatterCustomDao userChatterCustomDao;

    @Resource
    CommonUtilityService commonUtilityService;

    @NacosValue(value = "${app.icon}", autoRefreshed = true)
    private String appIcon;
    @Resource
    UserProfileDao userProfileDao;
    @Resource
    UserDao userDao;
    @Resource
    UserWlmDao userWlmDao;
    @Resource
    UserInterestsDao userInterestsDao;
    @Resource
    UserTaskDetailDao userTaskDetailDao;
    @Resource
    private UserConversationDao userConversationDao;
    @Resource
    private UserMsgSendTotalDao userMsgSendTotalDao;
    @NacosValue(value = "${default.user.chat.level:[{\"levelName\":\"0\",\"sortBy\":1,\"value\":0},{\"levelName\":\"1\",\"sortBy\":2,\"value\":5},{\"levelName\":\"2\",\"sortBy\":3,\"value\":15},{\"levelName\":\"3\",\"sortBy\":4,\"value\":30},{\"levelName\":\"4\",\"sortBy\":5,\"value\":60},{\"levelName\":\"5\",\"sortBy\":6,\"value\":100},{\"levelName\":\"6\",\"sortBy\":7,\"value\":150},{\"levelName\":\"7\",\"sortBy\":8,\"value\":220},{\"levelName\":\"8\",\"sortBy\":9,\"value\":300},{\"levelName\":\"9\",\"sortBy\":10,\"value\":400},{\"levelName\":\"10\",\"sortBy\":11,\"value\":999999}]}", autoRefreshed = true)
    private String defaultUserChatLevelConfig;




    public MsgAPI() {
        super();
    }

    /**
     * MECHAT: matchList消息发送
     */
    public JSONObject postMatchedRequest(AppEnum app, String toUserCode, Event event, Integer type) throws ApplicationException {
        logger.info("MsgAPI.postMatchedRequest pushSendRequest:{}", JSONObject.toJSONString(event));
        try {
            if (StringUtils.isEmpty(toUserCode) || StringUtils.isEmpty(event.getFromUserCode())) {
                logger.info("MsgAPI.postMatchedRequest userCode is null:{}", JSONObject.toJSONString(event));
                return null;
            }
            final String token = queryTokenByUserCode(app, toUserCode);
            if (StringUtils.isEmpty(token)) {
                logger.info("MsgAPI.postMatchedRequest token is null pushSendRequest:{}", JSONObject.toJSONString(event));
                return null;
            }
            Map<String, Object> params = Maps.newHashMap();
            /*
             * 消息回复需要的报文
             * type 1 回复消息  2普通照片  3私密照片  4普通视频  5私密视频 6 wlm喜欢
             * isNotification true 通知栏消息  false应用内消息
             * targetId 目标的userCode
             * imageUrl 对方发送的图片或者视频链接
             */
//            final Response<UserInfoDto> userBaseInfoRsp = userService.getUserByUserCode(event.getFromUserCode());
            Map<String, UserEntity> userEntityMap = commonUtilityService.getUserList(event.getFromUserCode(), event.getToUserCode());
            if (userEntityMap==null){
                logger.info("MsgAPI.postMatchedRequest userCode is deleted:{}", JSONObject.toJSONString(event));
                return null;
            }
            UserEntity userInfo = userEntityMap.get(event.getFromUserCode());
            UserEntity toUserInfo = userEntityMap.get(event.getToUserCode());
            if (AppEnum.MECHAT.equals(app)) {

                if (Objects.nonNull(userInfo)
                        && userInfo.getOnline() == OnlineStatus.ONLINE_STATUS.getType()) {
                    params.put("title", userInfo.getUserCode() + " got new match!");
                    params.put("notificationImage", ImagePrefixUtils.getFullImageUrl(userInfo.getAvatarUrl()));
                    params.put("body", "successfully matched with  [" + userInfo.getNickName() + "].");
                    if (userEntityMap.get(event.getToUserCode()) != null) {
                        params.put("imageUrl", ImagePrefixUtils.getFullImageUrl(toUserInfo.getAvatarUrl()));
                    }
                    params.put("targetId", event.getFromUserCode());
                    params.put("isNotification", Boolean.FALSE);
                }

            } else {

                final int online = toUserInfo.getOnline() == null ? OnlineStatus.OFFLINE_STATUS.getType() : toUserInfo.getOnline();
                if (OnlineStatus.ONLINE_STATUS.getType() == online) {
                    params.put("title", "Your crush likes you back!");
                    params.put("isNotification", Boolean.FALSE);
                    params.put("targetId", event.getFromUserCode());
                    params.put("notificationImage", ImagePrefixUtils.getFullImageUrl(userInfo.getAvatarUrl()));
                    if (userEntityMap.get(event.getToUserCode()) != null) {
                        params.put("imageUrl", ImagePrefixUtils.getFullImageUrl(toUserInfo.getAvatarUrl()));
                    }
                    params.put("body", "Go flirt now.");
                } else {
                    params.put("title", "Your crush likes you back！");
                    params.put("notificationImage", ImagePrefixUtils.getFullImageUrl(userInfo.getAvatarUrl()));
                    params.put("type", ParameterTypeEnum.MESSAGE_FEEDBACK.getId());
                    params.put("body", "Matched with " + userInfo.getNickName() + ". Go ahead and say hi!");
                    if (userEntityMap.get(event.getToUserCode()) != null) {
                        params.put("imageUrl", ImagePrefixUtils.getFullImageUrl(toUserInfo.getAvatarUrl()));
                    }
                    params.put("targetId", event.getFromUserCode());
                    params.put("isNotification", Boolean.TRUE);
                }


            }
            JSONObject pushSendRequest = buildRequestParams(app, token, String.valueOf(ParameterTypeEnum.MATCHED_PUSH.getId()), params, toUserCode);
            logger.info("MsgAPI.postMatchedRequest call start:{}, pushSendRequest:{}", toUserCode, pushSendRequest);
            final JSONObject result = super.post(pushSendRequest);

            // 存储调用结果
//            addTaskDetailRecords(type, pushSendRequest, result);

            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMatchedRequest call failed, toUserCode:{}", toUserCode, e);
            return null;
        }
    }

    private void addTaskDetailRecords(Integer type, JSONObject pushSendRequest, JSONObject result) {
        try {
            if (Objects.isNull(pushSendRequest) || Objects.isNull(result)) {
                return;
            }
            final JSONObject data = result.getJSONObject("data");
            if (Objects.isNull(data)) {
                return;
            }
            final int code = data.getIntValue("code");
            if (code != 0) {
                userTaskDetailDao.addHasExecutedTask(TaskTypeEnum.getEnumByCode(type), TaskStatusEnum.FAILED, pushSendRequest.toJSONString(), result.toJSONString());
            }
        } catch (Exception e) {
            logger.error("addTaskDetailRecordsFailed, type:{}, request:{}, result:{}", type, pushSendRequest.toJSONString(), result.toJSONString(), e);
        }
    }

    /**
     * MEBOO: 消息回复
     */
    public JSONObject postMessageFeedbackRequest(AppEnum app, String toUserCode, Integer type, Event event) throws ApplicationException {
        logger.info("MsgAPI.postMessageFeedbackRequest call start, toUserCode:{}, content:{}", toUserCode, JSONObject.toJSONString(event));
        try {
            if (StringUtils.isEmpty(toUserCode) || StringUtils.isEmpty(event.getFromUserCode())) {
                logger.info("MsgAPI.postMessageFeedbackRequest userCode is null:{}", JSONObject.toJSONString(event));
                return null;
            }
            final String token = queryTokenByUserCode(app, toUserCode);
            if (StringUtils.isEmpty(token)) {
                logger.info("MsgAPI.postMessageFeedbackRequest token is null pushSendRequest:{}", JSONObject.toJSONString(event));
                return null;
            }

            final JSONObject contentJson = Optional.ofNullable(JSONObject.parseObject(event.getContent())).orElse(new JSONObject());
            final Map<String, Object> contentExt = Maps.newHashMap();
            contentExt.put("notificationImage", contentJson.getString("notificationImage"));
            contentExt.put("title", contentJson.getString("title"));
            contentExt.put("body", contentJson.getString("body"));
            contentExt.put("isNotification", contentJson.getBoolean("isNotification"));
            contentExt.put("targetId", contentJson.getString("targetId"));
            contentExt.put("imageUrl", contentJson.getString("imageUrl"));

            JSONObject pushSendRequest = buildRequestParams(app, token, String.valueOf(type), contentExt, toUserCode);

            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postMessageFeedbackRequest call success, toUserCode:{}, content:{}, result:{}", toUserCode, pushSendRequest, result.toJSONString());
            // 存储调用结果
//            addTaskDetailRecords(type, pushSendRequest, result);
            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMessageFeedbackRequest call failed, toUserCode:{}, content:{}", toUserCode, event.getContent(), e);
            return null;
        }
    }

    @Resource
    ChatService chatService;
    /**
     * 发送消息到mechat
     */
    public JSONObject postMessageToMeChat(AppEnum app, String toUserCode, Integer type, Event event, JSONObject contentJson) throws ApplicationException {
        logger.info("MsgAPI.postMessageToMeChat call start, toUserCode:{}, content:{}", toUserCode, JSONObject.toJSONString(event));
        try {

            final Response<ChatListDto> modelUserCodeResponse = chatService.chatList(toUserCode, contentJson.getString("modelUserCode"), null,1,9999);

            if (modelUserCodeResponse == null || modelUserCodeResponse.getData() == null) {
                logger.info("MsgAPI.postMessageToMeChat, modelUserCodeResponse is null, toUserCode:{}, content:{}", toUserCode, JSONObject.toJSONString(event));
                return null;
            }

            final ChatListDto chatListDto = modelUserCodeResponse.getData();
            final List<UserAccount> conversationChatList = chatListDto.getConversationChatList();
            if (CollectionUtils.isEmpty(conversationChatList)) {
                logger.info("MsgAPI.postMessageToMeChat, conversationChatList is null, toUserCode:{}, content:{}", toUserCode, JSONObject.toJSONString(event));
                return null;
            }

            final List<UserAccount> singleUser = conversationChatList.stream().filter(o -> o.getUserCode().equals(event.getFromUserCode())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(singleUser)) {
                logger.info("MsgAPI.postMessageToMeChat, singleUser is null, toUserCode:{}, content:{}", toUserCode, JSONObject.toJSONString(event));
                return null;
            }

            final UserAccount chatUser = singleUser.get(0);
            String latestSendTime = chatUser.getLatestSendTime();
            if (latestSendTime != null) {
                Date date = DateUtil.parse(latestSendTime);
                // 判断日期是否为当天
                if (DateUtil.isSameDay(date, DateUtil.date())) {
                    // 转为年月日格式
                    chatUser.setLatestSendTime(DateUtil.format(date, "HH:mm"));
                } else {
                    // 判断日期是否为当年
                    if (DateUtil.year(date) == DateUtil.year(DateUtil.date())) {
                        // 转为月日格式
                        chatUser.setLatestSendTime(DateUtil.format(date, "MM-dd"));
                    } else {
                        // 转为年月日格式
                        chatUser.setLatestSendTime(DateUtil.formatDate(date));
                    }
                }
            }

            final Map<String, Object> content = Maps.newHashMap();
            content.put("token", event.getToUserCode());
            content.put("bizCode", contentJson.getString("bizCode"));
            content.put("userAccount", JSONObject.toJSONString(chatUser));
            content.put("modelUserCode", contentJson.getString("modelUserCode"));
            content.put("totalUnReadNum", chatListDto.getTotalUnReadNum());

            JSONObject pushSendRequest = new JSONObject();
            pushSendRequest.put("app", app.getAppCode());
            pushSendRequest.put("pushProvider", PushAPIEnum.WEB_SOCKET.getId());
            pushSendRequest.put("requestId", UUID.randomUUID().toString());
            pushSendRequest.put("content", JSONObject.toJSONString(content));


            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postMessageToMeChat call success, toUserCode:{}, content:{}, result:{}", toUserCode, pushSendRequest, result.toJSONString());

            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMessageToMeChat call failed, toUserCode:{}, content:{}", toUserCode, event.getContent(), e);
            return null;
        }
    }


    /**
     * 发送会员等级到mechat
     */
    public JSONObject postChatLevelToMeChat(AppEnum app, Event event, JSONObject contentJson) throws ApplicationException {
        logger.info("MsgAPI.postChatLevelToMeChat call start, event:{}", JSONObject.toJSONString(event));
        try {


            final Map<String, Object> content = Maps.newHashMap();
            content.put("token", event.getChatterUserCode());
            content.put("bizCode", contentJson.getString("bizCode"));
            content.put("userCode", event.getFromUserCode());
            content.put("modelUserCode", event.getToUserCode());
            content.put("chatLevel", contentJson.getInteger("chatLevel"));

            JSONObject pushSendRequest = new JSONObject();
            pushSendRequest.put("app", app.getAppCode());
            pushSendRequest.put("pushProvider", PushAPIEnum.WEB_SOCKET.getId());
            pushSendRequest.put("requestId", UUID.randomUUID().toString());
            pushSendRequest.put("content", JSONObject.toJSONString(content));


            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postChatLevelToMeChat call success, event:{}, result:{}", JSONObject.toJSONString(event), result.toJSONString());

            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMessageToMeChat call failed, event:{}", JSONObject.toJSONString(event), e);
            return null;
        }
    }

    /**
     * 发送消息到mechat
     */
    public JSONObject userLogOut(String userCode, String modelUserCode, String toUserCode) throws ApplicationException {
        logger.info("MsgAPI.userLogOut call start, userCode:{}, toUserCode:{}", userCode, toUserCode);
        try {

            final Map<String, Object> content = Maps.newHashMap();
            content.put("token", toUserCode);
            content.put("bizCode", "M20005");
            content.put("modelUserCode", modelUserCode);
            content.put("userCode", userCode);
            content.put("chatterUserCode", toUserCode);


            JSONObject pushSendRequest = new JSONObject();
            pushSendRequest.put("app",  AppEnum.MECHAT.getAppCode());
            pushSendRequest.put("pushProvider", PushAPIEnum.WEB_SOCKET.getId());
            pushSendRequest.put("requestId", UUID.randomUUID().toString());
            pushSendRequest.put("content", JSONObject.toJSONString(content));


            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.userLogOut call success, userCode:{}, toUserCode:{}, content:{}, result:{}", userCode, toUserCode, pushSendRequest, result.toJSONString());

            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.userLogOut call failed, fromUserCode:{}, toUserCode:{}", userCode, toUserCode, e);
            return null;
        }
    }


    /**
     * 发送消息到mechat
     */
    public JSONObject postRemindMessage(AppEnum app, String toUserCode, Event event) throws ApplicationException {
        logger.info("MsgAPI.postRemindMessage call start, toUserCode:{}, content:{}", toUserCode, JSONObject.toJSONString(event));
        try {

            JSONObject pushSendRequest = new JSONObject();
            pushSendRequest.put("app", app.getAppCode());
            pushSendRequest.put("pushProvider", PushAPIEnum.WEB_SOCKET.getId());
            pushSendRequest.put("requestId", UUID.randomUUID().toString());
            pushSendRequest.put("content", event.getContent());

            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postRemindMessage call success, toUserCode:{}, content:{}, result:{}", toUserCode, pushSendRequest, result.toJSONString());

            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postRemindMessage call failed, toUserCode:{}, content:{}", toUserCode, event.getContent(), e);
            return null;
        }
    }

    private Map<String, List<UserMsgSendTotalEntity>> getStringListMap(String modelUserCode) {
        final List<UserMsgSendTotalEntity> userMsgSendTotalEntities = userMsgSendTotalDao.queryByUserCode(null, modelUserCode);
        if (CollectionUtils.isEmpty(userMsgSendTotalEntities)) {
            return null;
        }
        return userMsgSendTotalEntities.parallelStream().collect(Collectors.groupingBy(UserMsgSendTotalEntity::getFromUserCode));
    }

    @Resource
    MemberService memberService;
    /**
     * MEBOO: Who like me
     */
    public JSONObject postMessageWhoLikeMeRequest(AppEnum app, String toUserCode, Event event, Integer type)
            throws ApplicationException {

        logger.info("MsgAPI.postMessageWhoLikeMeRequest call start, toUserCode:{},Event:{}", toUserCode, JSONObject.toJSONString(event));

        try {
            if (StringUtils.isEmpty(toUserCode) || StringUtils.isEmpty(event.getFromUserCode())) {
                logger.info("MsgAPI.postMessageWhoLikeMeRequest userCode is null:{}", JSONObject.toJSONString(event));
                return null;
            }
            final String token = queryTokenByUserCode(app, toUserCode);
            if (StringUtils.isEmpty(token)) {
                logger.info("MsgAPI.postMessageWhoLikeMeRequest token is null toUserCode:{},Event:{}", toUserCode, JSONObject.toJSONString(event));
                return null;
            }

            /*
             * 消息回复需要的报文
             * type 1 回复消息  2普通照片  3私密照片  4普通视频  5私密视频 6wlm喜欢
             * isNotification true 通知栏消息  false应用内消息
             * targetId 目标的userCode
             * imageUrl 对方发送的图片或者视频链接
             */
            Map<String, UserEntity> userEntityMap = commonUtilityService.getUserList(event.getFromUserCode(), event.getToUserCode());
            if (userEntityMap==null){
                logger.info("MsgAPI.postMatchedRequest userCode is deleted:{}", JSONObject.toJSONString(event));
                return null;
            }

            UserEntity userInfo = userEntityMap.get(event.getFromUserCode());
            UserEntity toUserInfo = userEntityMap.get(event.getToUserCode());
            Map<String, Object> params = new HashMap<>();
//            if (AppEnum.MEBOO.equals(app)) {

                final Response<Boolean> memberRsp = memberService.ifMember(toUserInfo.getUserCode());
                params.put("member", memberRsp == null ? Boolean.FALSE : memberRsp.getData());
                final int online = toUserInfo.getOnline() == null ? OnlineStatus.OFFLINE_STATUS.getType() : toUserInfo.getOnline();
                if (OnlineStatus.ONLINE_STATUS.getType() == online) {
                    params.put("title", "You Got A New Like!");
                    params.put("isNotification", Boolean.FALSE);
                    params.put("targetId", event.getFromUserCode());
                    params.put("notificationImage", ImagePrefixUtils.getFullImageUrl(userInfo.getAvatarUrl()));
                    params.put("body", userInfo.getNickName()+" liked you!");
                } else {
                    params.put("title", "You Got A New Like!");
                    params.put("notificationImage", ImagePrefixUtils.getFullImageUrl(userInfo.getAvatarUrl()));
                    params.put("type", ParameterTypeEnum.MESSAGE_FEEDBACK.getId());
                    params.put("body", "You have received a like.Go to check it out!");
                    params.put("targetId", event.getFromUserCode());
                    params.put("isNotification", Boolean.TRUE);
                }

//            }
            JSONObject pushSendRequest = buildRequestParams(app, token, String.valueOf(ParameterTypeEnum.WHO_LIKE_ME.getId()), params, toUserCode);

            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postMessageWhoLikeMeRequest call start, toUserCode:{}, result:{}", toUserCode, result.toJSONString());

            // 存储调用结果
//            addTaskDetailRecords(type, pushSendRequest, result);
            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMessageWhoLikeMeRequest call failed, toUserCode:{}", toUserCode, e);
            return null;
        }
    }

    /**
     * MEBOO: Who like me
     */
    public JSONObject postMessageWhoLikeMeRequest2(AppEnum app, String toUserCode, Event event, Integer type)
            throws ApplicationException {
        logger.info("MsgAPI.postMessageWhoLikeMeRequest2 call start, toUserCode:{},Event:{}",
                toUserCode, JSONObject.toJSONString(event));

        try {
            if (StringUtils.isEmpty(toUserCode)) {
                logger.info("MsgAPI.postMessageWhoLikeMeRequest2 userCode is null:{}", JSONObject.toJSONString(event));
                return null;
            }

            Map<String, UserEntity> userEntityMap = commonUtilityService.getUserList(event.getFromUserCode());
            if (userEntityMap==null){
                logger.info("MsgAPI.postMessageWhoLikeMeRequest2 userCode is deleted:{}", JSONObject.toJSONString(event));
                return null;
            }
            UserEntity modelInfo = userEntityMap.get(event.getFromUserCode());

            JSONObject pushSendRequest = new JSONObject();
            pushSendRequest.put("app", app.getAppCode());
            pushSendRequest.put("pushProvider", PushAPIEnum.WEB_SOCKET.getId());
            pushSendRequest.put("requestId", UUID.randomUUID().toString());
            final HashMap<String, Object> content = Maps.newHashMap();
            content.put("bizCode", "S20000");
            content.put("token", toUserCode);
            content.put("userCode", event.getFromUserCode());
            content.put("wlmUserInfo", JSONObject.toJSONString(getWlmDto(modelInfo, event.getFromUserCode())));
            pushSendRequest.put("content", JSONObject.toJSONString(content));

            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postMessageWhoLikeMeRequest2 call start, toUserCode:{}, result:{}", toUserCode, result.toJSONString());

            // 存储调用结果
            addTaskDetailRecords(type, pushSendRequest, result);

            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMessageWhoLikeMeRequest2 call failed, toUserCode:{}", toUserCode, e);
            return null;
        }
    }

    /**
     * MEBOO: 推送model在线状态
     */
    public JSONObject postModelOnlineStatusToUser(AppEnum app, String fromUserCode, String toUserCode, Event event,
                                                  Integer userType, String target, Integer online, Integer flashchatFlag, String modelUserCode)
            throws ApplicationException {
        logger.info("MsgAPI.postModelOnlineStatusToUser call start, fromUserCode:{}, toUserCode:{},Event:{}",
                fromUserCode, toUserCode, JSONObject.toJSONString(event));

        try {
            if (StringUtils.isEmpty(toUserCode)) {
                logger.info("MsgAPI.postModelOnlineStatusToUser userCode is null:{}", JSONObject.toJSONString(event));
                return null;
            }

            JSONObject pushSendRequest = new JSONObject();
            pushSendRequest.put("app", app.getAppCode());
            pushSendRequest.put("pushProvider", PushAPIEnum.WEB_SOCKET.getId());
            pushSendRequest.put("requestId", UUID.randomUUID().toString());
            final HashMap<String, Object> content = Maps.newHashMap();
            content.put("bizCode", target);
            content.put("token", toUserCode);
            content.put("userCode", event.getFromUserCode());
            content.put("userType",userType);
            content.put("online", online);
            content.put("flashchatFlag", flashchatFlag);
            content.put("modelUserCode", modelUserCode);
            pushSendRequest.put("content", JSONObject.toJSONString(content));

            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postModelOnlineStatusToUser call start, fromUserCode:{}, toUserCode:{}, result:{}", fromUserCode, toUserCode, result.toJSONString());

            // 存储调用结果
//            addTaskDetailRecords(type, pushSendRequest, result);

            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMessageWhoLikeMeRequest2 call failed, fromUserCode:{}, toUserCode:{}", fromUserCode, toUserCode, e);
            return null;
        }
    }

    /**
     * 封装WLM信息
     */
    public WlmUserDto getWlmDto(UserEntity o, String wlmUserCode) {
        // 获取userProfile信息
        final UserProfileEntity userProfileEntity = userProfileDao.queryUsersByUserCode(o.getUserCode());

        // 获取是否为新用户标记
        final List<UserWlmEntity> userWlmEntities = getUserWlmEntities(o.getUserCode(), wlmUserCode);
        Integer newFlag = null;
        if (CollectionUtils.isNotEmpty(userWlmEntities)) {
            newFlag = userWlmEntities.get(0).getNewFlag();
        }

        final UserEntity currentUser = userDao.selectByUserCode(wlmUserCode);

        String imageUrl = ImagePrefixUtils.getFullImageUrl(o.getAvatarUrl());

        WlmUserDto wlmUserDto = WlmUserDto.builder().build();
        wlmUserDto.setAboutMe(Objects.isNull(userProfileEntity) ? "" : userProfileEntity.getAboutMe());
        wlmUserDto.setAge(ageCalculation(o.getBirthday()));
        wlmUserDto.setUserCodeFriend(o.getUserCode());
        wlmUserDto.setInterests(getUserInterestDtos(o));
        wlmUserDto.setOnline(o.getOnline());
        wlmUserDto.setOnlineDesc(Objects.isNull(o.getOnline()) ? "" : OnlineStatus.fromType(o.getOnline()).getValue());
        Integer nearby = 0;
        if (Objects.nonNull(currentUser.getGpsPrivilege()) && currentUser.getGpsPrivilege() == 1) {
            if (UserType.CHATTER_MODEL.getType() == o.getUserType()) {
                nearby = 1;
            }
        }
        wlmUserDto.setNearby(nearby);
        wlmUserDto.setNewFlag(newFlag);
        wlmUserDto.setAvatarUrl(imageUrl);
        wlmUserDto.setLookingForDesc(GenderEnum.fromType(o.getLookingFor()).getValue());
        wlmUserDto.setGenderDesc(GenderEnum.fromType(o.getGender()).getValue());
        wlmUserDto.setNickName(o.getNickName());
        wlmUserDto.setUserCode(o.getUserCode());
        if (!org.springframework.util.StringUtils.isEmpty(o.getExtendInfo())) {
            ExtendInfoDto extendInfoDto = JSONUtil.toBean(o.getExtendInfo(), ExtendInfoDto.class);
            if (CollUtil.isNotEmpty(extendInfoDto.getTurnOnsList())) {
                wlmUserDto.setTurnOnsListSize(extendInfoDto.getTurnOnsList().size());
            }
        }

        return wlmUserDto;
    }

    /**
     * 年龄计算
     */
    private Integer ageCalculation(Date birthday) {
        Integer age = null;
        if (Objects.nonNull(birthday)) {
            try {
                age = TimeUtils.getAge(birthday);
            } catch (Exception e) {
                logger.error("Age calculation error, birthday:{}", birthday);
            }
        }
        return age;
    }
    /**
     * 获取用户兴趣
     */
    private List<UserInterestDto> getUserInterestDtos(UserEntity o) {
        // 查询用户兴趣
        final List<UserInterestsEntity> userInterestsEntities = getUserInterestsEntities(o.getUserCode());

        // 处理兴趣
        return userInterestsEntities.stream().map(inst -> UserInterestDto.builder().userCode(inst.getUserCode()).interestCode(inst.getInterestCode()).interest(inst.getInterest()).build()).collect(Collectors.toList());
    }

    private List<UserInterestsEntity> getUserInterestsEntities(String userCode) {
        return Optional.ofNullable(userInterestsDao.queryUsers(userCode)).orElse(Lists.newArrayList());
    }

    private List<UserWlmEntity> getUserWlmEntities(String userCode, String userCodeWlm) {
        UserWlmEntity param = new UserWlmEntity();
        param.setUserCode(userCode);
        param.setUserCodeWlm(userCodeWlm);
        return Optional.ofNullable(userWlmDao.selectByWlmUserCode(param)).orElse(Lists.newArrayList());
    }


    /**
     * MEBOO: Who like me
     */
    public JSONObject postMessageAvatarChange(AppEnum app, String fromUserCode, String toUserCode, Event event, Integer type)
            throws ApplicationException {
        logger.info("MsgAPI.postMessageAvatarChange call start, fromUserCode:{}, toUserCode:{},Event:{}",
                fromUserCode, toUserCode, JSONObject.toJSONString(event));

        try {
            if (StringUtils.isEmpty(toUserCode)) {
                logger.info("MsgAPI.postMessageAvatarChange userCode is null:{}", JSONObject.toJSONString(event));
                return null;
            }
            // 获取model信息
            Map<String, UserEntity> userEntityMap = commonUtilityService.getUserList(fromUserCode);
            if (userEntityMap==null){
                logger.info("MsgAPI.postMessageAvatarChange userCode is deleted:{}", JSONObject.toJSONString(event));
                return null;
            }
            UserEntity userInfo = userEntityMap.get(fromUserCode);

            JSONObject pushSendRequest = new JSONObject();
            pushSendRequest.put("app", app.getAppCode());
            pushSendRequest.put("pushProvider", PushAPIEnum.WEB_SOCKET.getId());
            pushSendRequest.put("requestId", UUID.randomUUID().toString());
            final HashMap<String, Object> content = Maps.newHashMap();
            content.put("bizCode", "S20001");
            content.put("token", toUserCode);
            content.put("userCode", userInfo.getUserCode());
            content.put("nickName", userInfo.getNickName());
            content.put("avatarUrl", ImagePrefixUtils.getFullImageUrl(userInfo.getAvatarUrl()));
//            content.put("wlmUserInfo", JSONObject.toJSONString(getWlmDto(userInfo, event.getToUserCode())));

            pushSendRequest.put("content", JSONObject.toJSONString(content));

            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postMessageAvatarChange call end, toUserCode:{}, result:{}", toUserCode, result.toJSONString());

            // 存储调用结果
            addTaskDetailRecords(type, pushSendRequest, result);
            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMessageAvatarChange call failed, toUserCode:{}", toUserCode, e);
            return null;
        }
    }

    /**
     * 举报消息推送
     */
    public JSONObject postRequestMessageRequest(AppEnum app, String toUserCode, Event event, Integer type)
            throws ApplicationException {
        logger.info("MsgAPI.postRequestMessageRequest call start, toUserCode:{},Event:{}",
                toUserCode, JSONObject.toJSONString(event));

        try {
            if (StringUtils.isEmpty(toUserCode) || StringUtils.isEmpty(event.getFromUserCode())) {
                logger.info("MsgAPI.postRequestMessageRequest userCode is null:{}",
                        JSONObject.toJSONString(event));
                return null;
            }
            final String token = queryTokenByUserCode(app, toUserCode);
            if (StringUtils.isEmpty(token)) {
                logger.info("MsgAPI.postRequestMessageRequest token is null toUserCode:{},Event:{}",
                        toUserCode, JSONObject.toJSONString(event));
                return null;
            }

            /*
             * 消息回复需要的报文
             * type 1 回复消息  2普通照片  3私密照片  4普通视频  5私密视频 6wlm喜欢
             * isNotification true 通知栏消息  false应用内消息
             * targetId 目标的userCode
             * imageUrl 对方发送的图片或者视频链接
             */

            Map<String, UserEntity> userEntityMap = commonUtilityService.getUserList(event.getFromUserCode(), event.getToUserCode());
            if (userEntityMap==null){
                logger.info("MsgAPI.postRequestMessageRequest userCode is deleted:{}", JSONObject.toJSONString(event));
                return null;
            }
            UserEntity userInfo = userEntityMap.get(event.getFromUserCode());
            UserEntity toUserInfo = userEntityMap.get(event.getToUserCode());
            Map<String, Object> params = new HashMap<>();
            if (AppEnum.MEBOO.equals(app) || AppEnum.PP.equals(app)) {
                final int online = toUserInfo.getOnline() == null ?
                        OnlineStatus.OFFLINE_STATUS.getType() : toUserInfo.getOnline();
                if (OnlineStatus.ONLINE_STATUS.getType() == online) {
                    params.put("title", "You Got A New Message!");
                    params.put("isNotification", Boolean.FALSE);
                    params.put("targetId", event.getFromUserCode());
//                    params.put("notificationImage", ServiceUtils.getImageUrl(userInfo.getAvatarUrl(),photoPrefix));
//                    params.put("body", "Thank you!Your message has been received!We will try to review as soon as possible.");
                } else {
                    params.put("title", "You Got A New Message!");
                    params.put("notificationImage", ImagePrefixUtils.getFullImageUrl(userInfo.getAvatarUrl()));
                    params.put("type", ParameterTypeEnum.MESSAGE_FEEDBACK.getId());
                    params.put("body", "Thank you!Your message has been received!We will try to review as soon as possible.");
                    params.put("targetId", event.getFromUserCode());
                    params.put("isNotification", Boolean.TRUE);
                }

            }
            JSONObject pushSendRequest = buildRequestParams(app, token, String.valueOf(ParameterTypeEnum.WHO_LIKE_ME.getId()), params, toUserCode);

            final JSONObject result = super.post(pushSendRequest);
            logger.info("MsgAPI.postMessageWhoLikeMeRequest call start, toUserCode:{}, result:{}", toUserCode, result.toJSONString());

            // 存储调用结果
//            addTaskDetailRecords(type, pushSendRequest, result);
            return null;
        } catch (Exception e) {
            logger.error("MsgAPI.postMessageWhoLikeMeRequest call failed, toUserCode:{}", toUserCode, e);
            return null;
        }
    }

    /**
     * notice消息发送
     */
    @Resource
    TMessageDao messageDao;

    public JSONObject postNoticeRequest(String targetUserCode) throws ApplicationException {
        if (StringUtils.isEmpty(targetUserCode)) {
            return null;
        }
        try {

            final List<TMessageEntity> messages = messageDao.queryUnReadMessages(targetUserCode);
            if (CollectionUtils.isEmpty(messages)) {
                return null;
            }

            final String token = queryTokenByUserCode(targetUserCode);
            if (StringUtils.isEmpty(token)) {
                return null;
            }
            Map<String, Object> params = Maps.newHashMap();
            params.put("targetId", targetUserCode);
            params.put("isNotification", Boolean.TRUE);
            JSONObject pushSendRequest = buildRequestParams(AppEnum.MECHAT, token, String.valueOf(ParameterTypeEnum.SYSTEM_NOTICE.getId()), params, targetUserCode);

            final JSONObject result = super.post(pushSendRequest);

            return result;

        } catch (Exception e) {
            logger.error("MsgAPI.postMatchedRequest call failed, toUserCode:{}", targetUserCode, e);
            return null;
        }
    }

    private JSONObject buildRequestParams(AppEnum app, String token, String type, Map<String, Object> contentMap, String toUserCode) {

        JSONObject pushSendRequest = new JSONObject();
        pushSendRequest.put("app", app.getAppCode());
        pushSendRequest.put("pushProvider", PushAPIEnum.FCM.getId());
        pushSendRequest.put("requestId", UUID.randomUUID().toString());
        final HashMap<String, Object> content = Maps.newHashMap();
        content.put("type", type);
        content.put("token", token);
        if (Objects.nonNull(contentMap)) {
            content.putAll(contentMap);
        }
        if (StringUtils.isNotEmpty(toUserCode)) {
            final UserEntity toUser = userDao.selectByUserCode(toUserCode);
            if (Objects.nonNull(toUser)) {
                pushSendRequest.put("appCode", StringUtils.isEmpty(toUser.getAppCode()) ? "sparksy" : toUser.getAppCode());
            }
        }

        pushSendRequest.put("content", JSONObject.toJSONString(content));
        return pushSendRequest;
    }

    /**
     * 获取用户token, 如果是往mechat推送，需要查询chatter的用户码
     */
    private String queryTokenByUserCode(AppEnum appEnum, String userCode) {
        if (StringUtils.isEmpty(userCode)) {
            return null;
        }
        String forUser = null;
        if (AppEnum.MECHAT.equals(appEnum)) {
            final List<UserModelEntity> chatters = userChatterCustomDao.queryChatters(userCode);
            if (CollectionUtils.isEmpty(chatters)) {
                return null;
            }
            forUser = chatters.get(0).getChatterUserCode();
        } else {
            forUser = userCode;
        }



        Map<String, Object> params = Maps.newHashMap();
        params.put("bizType", BizTypeEnum.GOOGLE.getCode());
        params.put("userCode", forUser);
        params.put("deleted", 0);
        final List<UserAccessEntity> userAccessEntities = userAccessDao.selectByParams(params);
        if (CollectionUtils.isEmpty(userAccessEntities)) {
            return null;
        }
//        logger.info("=====getToken==== params:{}, result:{}",params,JSONObject.toJSONString(userAccessEntities));


        return userAccessEntities.get(0).getToken();
    }

    private String queryTokenByUserCode(String userCode) {

        Map<String, Object> params = Maps.newHashMap();
        params.put("userCode", userCode);
        params.put("bizType", BizTypeEnum.GOOGLE.getCode());
        params.put("deleted", 0);
        final List<UserAccessEntity> userAccessEntities = userAccessDao.selectByParams(params);
        if (CollectionUtils.isEmpty(userAccessEntities)) {
            return null;
        }
        return userAccessEntities.get(0).getToken();
    }

    public JSONObject sendBackMessage(AppEnum app, String targetUserCode, String title, String content) {
        final String token = queryTokenByUserCode(app, targetUserCode);
        Map<String, Object> params = new HashMap<>();
        params.put("title", title);
        params.put("notificationImage", "https://storage.googleapis.com/meboo-online-b68e7.appspot.com/images/meboo-icon.png");
        params.put("type", ParameterTypeEnum.MESSAGE_FEEDBACK.getId());
        params.put("body", content);
//        params.put("imageUrl", ServiceUtils.getImageUrl(toUserInfo.getAvatarUrl(), photoPrefix));
        params.put("targetId", targetUserCode);
        params.put("isNotification", Boolean.TRUE);
        JSONObject pushSendRequest = buildRequestParams(app, token, String.valueOf(ParameterTypeEnum.MATCHED_PUSH.getId()), params, targetUserCode);
        logger.info("MsgAPI.postMatchedRequest call start:{}, pushSendRequest:{}", targetUserCode, pushSendRequest);
        final JSONObject result = super.post(pushSendRequest);
        return result;
    }


    public JSONObject sendBackMessage(AppEnum app, String targetUserCode, String title, String content, String overTimeContent, Integer overTime) {
        final String token = queryTokenByUserCode(app, targetUserCode);
        Map<String, Object> params = new HashMap<>();
        params.put("title", title);
        params.put("notificationImage", "https://storage.googleapis.com/meboo-online-b68e7.appspot.com/images/meboo-icon.png");
        params.put("type", ParameterTypeEnum.PRODUCT_PROMOTION.getId());
        params.put("body", content);
        params.put("overTimeContent", overTimeContent);
        params.put("overTime", overTime);

//        params.put("imageUrl", ServiceUtils.getImageUrl(toUserInfo.getAvatarUrl(), photoPrefix));
        params.put("targetId", targetUserCode);
        params.put("isNotification", Boolean.FALSE);
        JSONObject pushSendRequest = buildRequestParams(app, token, String.valueOf(ParameterTypeEnum.MATCHED_PUSH.getId()), params, targetUserCode);
        logger.info("MsgAPI.postMatchedRequest call start:{}, pushSendRequest:{}", targetUserCode, pushSendRequest);
        final JSONObject result = super.post(pushSendRequest);
        return result;
    }

    public JSONObject conversationRemove(AppEnum app, String targetUserCode, String title, String content) {
        final String token = queryTokenByUserCode(app, targetUserCode);
        Map<String, Object> params = new HashMap<>();
        params.put("title", title);
        params.put("notificationImage", "https://storage.googleapis.com/meboo-online-b68e7.appspot.com/images/meboo-icon.png");
        params.put("type", ParameterTypeEnum.REMOVE_CONVERSATION.getId());
        params.put("body", content);
//        params.put("imageUrl", ServiceUtils.getImageUrl(toUserInfo.getAvatarUrl(), photoPrefix));
        params.put("targetId", targetUserCode);
        params.put("isNotification", Boolean.TRUE);
        JSONObject pushSendRequest = buildRequestParams(app, token, String.valueOf(ParameterTypeEnum.MATCHED_PUSH.getId()), params, targetUserCode);
        logger.info("MsgAPI.postMatchedRequest call start:{}, pushSendRequest:{}", targetUserCode, pushSendRequest);
        final JSONObject result = super.post(pushSendRequest);
        return result;
    }
}
